﻿Imports System.Data.SqlClient
Imports System.Xml.Serialization
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Xml

<DataContract()>
Public Class MsSqlToNhibCS

    <DataMember()>
    Public Property Name As String = ""

    <DataMember()>
    Public Property WorkingDirectory As String = ""

    <DataMember()>
    Public Property ConnStrBld As SqlConnectionStringBuilder = New SqlConnectionStringBuilder

    Public ProjectPath As String = Nothing

    Public Sub run()
        If String.IsNullOrEmpty(Me.WorkingDirectory) OrElse Not My.Computer.FileSystem.DirectoryExists(Me.WorkingDirectory) Then
            MessageBox.Show("Invalid working directory.")
            Exit Sub
        End If

        Dim SrvReader As New SqlServerMetadataReader(Me.ConnStrBld.ConnectionString)
        Dim sol As New List(Of SelectedObject)
        Dim TablesList As List(Of Table) = SrvReader.GetTables("dbo")

        'TODO: Move to GUI
        'Dim SelectedTables() As String = {"Doctors", "Spec"} ' "Founds", "Tests", "Profiles"}
        For Each CurTbl As Table In TablesList
            sol.Add(New SelectedObject(False, CurTbl.Name))
        Next
        Dim f As New FormSelectObjects
        f.DataGridView1.DataSource = sol
        f.ShowDialog()
        Dim SelectedTables() As String = sol.Where(Function(o) o.IsSelected).Select(Function(o) o.Name).ToArray

        'Following code just demonstrates idea

        '1.Create XML data
        '1.1. Read database objects
        'Dim ConStr As String = My.Computer.FileSystem.ReadAllText(Path.Combine(DOCS_PATH, "MyCon.txt"))


        '1.2. Build XML with them
        Dim XDoc As New XmlDocument
        Dim Decl As XmlDeclaration = XDoc.CreateXmlDeclaration("1.0", "utf-8", "yes")
        XDoc.AppendChild(Decl)
        Dim RootNode As XmlNode = XDoc.CreateElement("Database")
        XDoc.AppendChild(RootNode)
        Dim TablesNode As XmlNode = RootNode.AppendChild(XDoc.CreateElement("Tables"))

        'Dim i As Integer = 0

        For Each CurTbl As Table In TablesList
            'Dim CurTableNode As XmlNode = TablesNode.AppendChild(XDoc.CreateElement("Table"))
            'CurTableNode.InnerXml = CurRow.Name
            If SelectedTables.Contains(CurTbl.Name) Then
                CurTbl.Columns = SrvReader.GetTableDetails(CurTbl, "dbo")
                TablesNode.AppendChild(XDoc.ImportNode(SerializeHelper.ObjToXMLElement(CurTbl), True))
            End If
            'i += 1
            'If i >= 1 Then Exit For
        Next

        Dim XMLFileName As String = Path.Combine(Me.WorkingDirectory, "FullData.xml")
        XDoc.Save(XMLFileName)

        'Process.Start(XMLFileName)


        Dim IteratorNodes As XmlNodeList = XDoc.SelectNodes("/Database/Tables/Table")
        For Each CurNode As XmlNode In IteratorNodes
            Dim TempFileName As String = Path.Combine(Me.WorkingDirectory, "Data.xml")
            My.Computer.FileSystem.WriteAllText(TempFileName, CurNode.OuterXml, False)

            '2. Start PHP as template engine and grab the output
            Dim oProcess As New Process()
            Dim oStartInfo As New ProcessStartInfo(My.Settings.PHPPath,
                                                   Path.Combine(
                                                       Path.Combine(My.Application.Info.DirectoryPath, "Templates"),
                                                       "NHibernateAttributes.php"))
            oStartInfo.WorkingDirectory = Me.WorkingDirectory
            oStartInfo.WindowStyle = ProcessWindowStyle.Minimized
            oStartInfo.UseShellExecute = False
            oStartInfo.RedirectStandardOutput = True
            oProcess.StartInfo = oStartInfo
            oProcess.Start()
            Dim sOutput As String
            Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
                sOutput = oStreamReader.ReadToEnd()
            End Using

            '3.Save produced file
            My.Computer.FileSystem.WriteAllText(Path.Combine(Me.WorkingDirectory, CurNode.SelectSingleNode("descendant::TableName").InnerText & ".cs"), sOutput, False)
        Next

        'MessageBox.Show("Done.")
    End Sub

    Public Sub New()
        Me.ConnStrBld = New SqlConnectionStringBuilder
    End Sub

    Public Sub New(Name As String)
        Me.New()
        Me.Name = Name
    End Sub

    Public Sub ShowProperties()
        Dim f As New Windows.Forms.Form
        Dim pg As New PropertyGrid
        pg.Dock = DockStyle.Fill
        pg.SelectedObject = Me '.ConnStrBld
        f.Controls.Add(pg)
        f.ShowDialog()
    End Sub

    Public Sub Save(Optional ByRef FileName As String = Nothing)
        If String.IsNullOrEmpty(FileName) AndAlso Not String.IsNullOrEmpty(Me.ProjectPath) Then
            FileName = Me.ProjectPath
        End If
        If String.IsNullOrEmpty(FileName) OrElse Not My.Computer.FileSystem.FileExists(FileName) Then
            Dim dlg As New SaveFileDialog()
            dlg.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            dlg.Title = "Save Project"
            dlg.Filter = "SimpleGen Projects|*.sgp|All Files|*.*"
            If Not dlg.ShowDialog() = DialogResult.OK Then Exit Sub
            FileName = dlg.FileName
        End If
        Dim ser As New DataContractSerializer(GetType(MsSqlToNhibCS))
        Using xr As New FileStream(FileName, FileMode.OpenOrCreate)
            ser.WriteObject(xr, Me)
            xr.Flush()
        End Using
    End Sub

    Public Shared Function GetFtomFile(FileName As String) As MsSqlToNhibCS
        Dim ser As New DataContractSerializer(GetType(MsSqlToNhibCS))
        Using xr As New FileStream(FileName, FileMode.Open)
            Dim rv As MsSqlToNhibCS = CType(ser.ReadObject(xr), MsSqlToNhibCS)
            rv.ProjectPath = FileName
            If rv.ConnStrBld Is Nothing Then rv.ConnStrBld = New SqlConnectionStringBuilder
            Return rv
        End Using
    End Function



End Class
